package com.ordobill.webapp.action;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Vector;

import javax.servlet.http.*;

import org.apache.struts.action.*;
import org.apache.commons.logging.*;
import com.ibatis.sqlmap.client.*;
import com.ordobill.webapp.beans.FigInform;
import com.ordobill.webapp.beans.Figures;
import com.ordobill.webapp.beans.Modeling;
import com.ordobill.webapp.beans.Project;
import com.ordobill.webapp.beans.SimulationFields;
import com.ordobill.webapp.common.Constants;
import com.ordobill.webapp.common.SimulationEngineImpl;
import com.ordobill.webapp.common.SqlMapClientManager;

import org.apache.struts.actions.*;

public class ProjectAction extends DispatchAction{
    
    private Log log = LogFactory.getFactory().getInstance(this.getClass().getName());
    private SqlMapClient sqlMap = SqlMapClientManager.getSqlMapClient();
    
    //Flex에서 언제나 호출 할 수 있게 static으로 SimulationFields를만들었습니다.
    //RemoteJava의 58라인을 확인하세요
    public static HashMap<String, SimulationFields[]> simulationArr = new HashMap<String, SimulationFields[]>();

    /**
     * 프로젝트의 리스트를 보여줍니다.
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    public ActionForward list(ActionMapping mapping,
                               ActionForm form,
                               HttpServletRequest request,
                               HttpServletResponse response) throws Exception {
        
        Project projectForm = (Project)form;
        HttpSession session = request.getSession();
     
        // 2012-02-07 정재우 실장님의 요청으로 등급별 리스트 조회 조건 추가함 ( UserLevel 1:관리자(전체)/ 0:일반(본인) 리스트 구분)
        if("0".equals((String)session.getAttribute("loginUserLevel"))) {
            projectForm.setProId((String)session.getAttribute("unitIDInSession"));
        }else{
            projectForm.setProId("");
        }

        ArrayList<Project> projectList = (ArrayList<Project>) sqlMap.queryForList("Project.list", projectForm);
        int totalCount = (Integer) sqlMap.queryForObject("Project.listCount", projectForm);
        
        request.setAttribute("projectList", projectList);
        request.setAttribute("projectForm", projectForm);
        request.setAttribute("totalCount", totalCount);
        
        return mapping.findForward("list");
    }
    
    /**
     * 프로젝트의 정보를 보여줍니다.
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ActionForward info(ActionMapping mapping,
                              ActionForm form,
                              HttpServletRequest request,
                              HttpServletResponse response) throws Exception {
        Project projectForm = (Project)form;
        Project projectData = (Project)sqlMap.queryForObject("Project.list", projectForm);
        
        request.setAttribute("projectData", projectData);

        return mapping.findForward("info");
    }
    
    /**
     * 모델링 페이지로가는 ActionForward입니다.
     * 
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return ActionMapping
     * @throws Exception
     */
    @SuppressWarnings("unused")
    public ActionForward model(ActionMapping mapping,
                                ActionForm form,
                                HttpServletRequest request,
                                HttpServletResponse response) throws Exception {
        Project projectForm = (Project)form;
        return mapping.findForward("model");
    }
    
    /**
     * 프로젝트를 저장합니다.
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ActionForward insert(ActionMapping mapping,
                                ActionForm form,
                                HttpServletRequest request,
                                HttpServletResponse response) throws Exception {
        
        Project projectForm = (Project)form;
        ActionMessages msg = new ActionMessages();
        int message = -1;
        message = (Integer) sqlMap.insert("Project.projectInsert", projectForm);
        
        if(message == 0){
            msg.add("message", new ActionMessage("저장에 실패했습니다."));
        }else if(message > 0){
            msg.add("message", new ActionMessage("저장에 성공했습니다."));
        }
        
        saveMessages(request, msg);
        
        request.setAttribute("projectData", projectForm);
        return mapping.findForward("success");
    }
    
    /**
     * 시뮬레이션을 위한 기초값을 넣는 Method입니다.
     * Method for Input base on variable of simulation
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ActionForward simulatorBase(ActionMapping mapping,
                                   ActionForm form,
                                   HttpServletRequest request,
                                   HttpServletResponse response) throws Exception {
            Project projectForm = (Project)form;
            projectForm = (Project) sqlMap.queryForObject("Project.list", projectForm);
            request.setAttribute("projectForm", projectForm);
            return mapping.findForward("simulatorBase");
    }
    
    /**
     * 시뮬레이션의 기본 화면을 위한 Method입니다.
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    public ActionForward simulator(ActionMapping mapping,
                                   ActionForm form,
                                   HttpServletRequest request,
                                   HttpServletResponse response) throws Exception {
        Project projectForm = (Project)form;
        HttpSession session = request.getSession(false);
        if(simulationArr !=null && !simulationArr.isEmpty()){
            simulationArr.remove((String)session.getAttribute(Constants.SESSION_GETID));
        }
        log.debug("Iteration Number   ========="+projectForm.getProIterNum());
        log.debug("Startting Time     ========="+projectForm.getProStartTime());
        log.debug("Life      Time     ========="+projectForm.getProLifeTime());
        log.debug("Time      Division ========="+projectForm.getProTd());
        
        Project simBaseForm = (Project) sqlMap.queryForObject("Project.list", projectForm);
        ArrayList<Figures> figList = (ArrayList<Figures>) sqlMap.queryForList("Figures.list", new Figures(projectForm));
        
        request.setAttribute("simBaseForm", simBaseForm);
        request.setAttribute("figList", figList);
        return mapping.findForward("simulator");
    }
    
    /**
     * 시뮬레이션을 실행합니다.
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    public ActionForward runSimulator(ActionMapping mapping,
                                       ActionForm form,
                                       HttpServletRequest request,
                                       HttpServletResponse response)throws Exception{
        Project projectForm = (Project)form;
        HttpSession session = request.getSession(false);
        if(simulationArr !=null && !simulationArr.isEmpty()){
            simulationArr.remove(session.getAttribute(Constants.SESSION_GETID));
        }
        log.debug("Iteration Number   ========="+projectForm.getProIterNum());
        log.debug("Startting Time     ========="+projectForm.getProStartTime());
        log.debug("Life      Time     ========="+projectForm.getProLifeTime());
        log.debug("Time      Division ========="+projectForm.getProTd());
        
        //2012-01-13 정재우 실장님의 요청으로 추가함
        ActionMessages msg = new ActionMessages();
        int message = -1;
        message = (Integer) sqlMap.update("Project.simulatorUpdate", projectForm);
               if(message == 0){
                   msg.add("message", new ActionMessage("저장에 실패했습니다."));
               }else if(message > 0){
                   msg.add("message", new ActionMessage("저장에 성공했습니다."));
               }
        saveMessages(request, msg);
        
        List modelingList =  sqlMap.queryForList("Modeling.getModeling", ""+projectForm.getProUid());
        Vector<Modeling> modelingVector = new Vector<Modeling>(modelingList.size());
        modelingVector.addAll(modelingList);
        
        ArrayList<Figures> figList = (ArrayList<Figures>) sqlMap.queryForList("Figures.figures", new Figures(projectForm));
        
        SimulationEngineImpl simCal = new SimulationEngineImpl(projectForm);
        simulationArr.put((String)session.getAttribute(Constants.SESSION_GETID), simCal.simulationBody(modelingVector));
        
        ArrayList<FigInform> figInformList;
        for(Figures fig : figList){
            figInformList = new ArrayList<FigInform>();
            for(FigInform inFig : simCal.getFigInformList()){
                if(fig.getFigUid() == inFig.getFigUid()){
                    figInformList.add(inFig);
                }
            }
            fig.setFigInform(figInformList);
            figInformList = null;
        }

        request.setAttribute("simBaseForm", projectForm);
        request.setAttribute("figList", figList);
        request.setAttribute("simulationArr", simulationArr.get((String)session.getAttribute(Constants.SESSION_GETID)));
        return mapping.findForward("simulator");
    }
    
    /**
     * 프로젝트의 값을 수정합니다.
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ActionForward update(ActionMapping mapping,
                                ActionForm form,
                                HttpServletRequest request,
                                HttpServletResponse response) throws Exception {
        Project projectForm = (Project)form;
        ActionMessages msg = new ActionMessages();
        int message = -1;
        message = (Integer) sqlMap.update("Project.projectUpdate", projectForm);
               if(message == 0){
                   msg.add("message", new ActionMessage("저장에 실패했습니다."));
               }else if(message > 0){
                   msg.add("message", new ActionMessage("저장에 성공했습니다."));
               }
        saveMessages(request, msg);               
        request.setAttribute("projectData", projectForm);
        return mapping.findForward("update");
    }
    
    /**
     * 프로젝트의 값을 수정합니다.
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ActionForward simulationUpdate(ActionMapping mapping,
                                ActionForm form,
                                HttpServletRequest request,
                                HttpServletResponse response) throws Exception {
        Project projectForm = (Project)form;
        ActionMessages msg = new ActionMessages();
        int message = -1;
        message = (Integer) sqlMap.update("Project.simulatorUpdate", projectForm);
               if(message == 0){
                   msg.add("message", new ActionMessage("저장에 실패했습니다."));
               }else if(message > 0){
                   msg.add("message", new ActionMessage("저장에 성공했습니다."));
               }
        saveMessages(request, msg);               
        request.setAttribute("projectForm", projectForm);
        return mapping.findForward("simulatorUpdate");
    }    
    
    /**
     * 프로젝트를 삭제합니다.
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ActionForward delete(ActionMapping mapping,
            ActionForm form,
            HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        Project projectForm = (Project)form;
        ActionMessages msg = new ActionMessages();
        int message = -1;
            message = (Integer) sqlMap.delete("Project.projectDelete", projectForm);  // PROJECT
                                sqlMap.delete("Project.modelingDelete", projectForm); // MODELING 
                                sqlMap.delete("Project.figuresDelete", projectForm);  // FIGURES
            if(message == 0){
                msg.add("message", new ActionMessage("삭제에 실패했습니다."));
            }else if(message > 0){
                msg.add("message", new ActionMessage("삭제에 성공했습니다."));
            }
            saveMessages(request, msg);
                request.setAttribute("projectData", projectForm);
        return mapping.findForward("delete");
    }
}
